package com.hsh.controller;

import com.hsh.bean.BootStrapComment;
import com.hsh.bean.Comment;
import com.hsh.bean.User;
import com.hsh.service.CommentService;
import com.hsh.service.UserService;
import com.hsh.util.ToBootStrapUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private UserService userService;

    @RequestMapping("/list")
    public String list(Integer uid, Model model) {
        User user = userService.findById(uid);
        model.addAttribute("user", user);
        System.out.println("commentController---list---user---"+user);
        return "/comment/list";
    }

    @RequestMapping("/info")
    public String info(Integer uid, Integer cid, Model model){
        //获取当前登录的用户
        User user = userService.findById(uid);
        model.addAttribute("user", user);
        //获取父话题
        BootStrapComment comment =
                ToBootStrapUtil.getBootStrapComment(commentService.findByCid(cid));
        model.addAttribute("comment", comment);
//        //获取子话题
//        List<Comment> commentInfo = commentService.findCommentInfo(comment.getCid());
//        commentInfo.forEach(System.out::println);
//        List<BootStrapComment> commentList = new ArrayList<>();
//        for (Comment c : commentInfo){
//            BootStrapComment pageData = ToBootStrapUtil.getBootStrapComment(c);
//            commentList.add(pageData);
//        }
//        model.addAttribute("commentList", commentList);
        return "/comment/info";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "/sleep/add";
    }

    @RequestMapping("/add")
    public String add(Comment comment, Model model){

        System.out.println("commentController---add---");
        System.out.println(comment);
        comment.setCTargetId(comment.getCTargetId());
        comment.setCid(null);

        commentService.insert(comment);

        System.out.println(comment);
        return "redirect:/comment/info?uid="+comment.getUid()+"&cid="+comment.getCTargetId();
    }

    @RequestMapping("/toUpdate/{cid}")
    public String toUpdate(Integer cid, Model model){
        Comment comment = commentService.findByCid(cid);
        model.addAttribute("comment", comment);
        return "/comment/update";
    }

    @RequestMapping("/update")
    public String update(Comment comment){
        comment.setCDate(new Date());
        commentService.update(comment);
        return "redirect:/comment/list";
    }


}
